package com.zcx.zuul.Filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

import java.io.UnsupportedEncodingException;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author zhaochangxin
 * @date 2022/3/7 11:57
 * 登陆拦截
 * 类继承ZuulFilter
 */
@Component
@Slf4j
public class AuthFilter extends ZuulFilter {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    // 排除过滤的 uri 地址
    private static final String LOGIN_URI = "/zcxtest/user/login";
    private static final String REGISTER_URI = "/zcxtest/user/register";

    // 请求处理类型
    @Override
    public String filterType() {
        //pre:在请求转发前生效
        //routing：处理请求前
        //post：请求处理完成后
        //error：请求处理失败
        return PRE_TYPE;
    }

    // 过滤器排序，值越小，排序越靠前
    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 是否生效
        // 获取http请求
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        log.info("url:{}", request.getRequestURI());
        // 获取url如果等于/user/login则返回false，不启用filter
        if (LOGIN_URI.equals(request.getRequestURI()) ||
                REGISTER_URI.equals(request.getRequestURI())) {
            return false;
        } else {
            // 否则返回true启用filter
            return true;
        }
    }

    /**
     * @return
     * @throws ZuulException
     * 判断是否有token头 进行验证方法
     */
    @Override
    public Object run() throws ZuulException {
        // 过滤器逻辑
        // 获取请求上下文
        RequestContext context = RequestContext.getCurrentContext();
        // 获取http请求
        HttpServletRequest request = context.getRequest();
        String token = request.getHeader("token");
        try {
            verifyToken(context, token);
        }catch (JWTVerificationException e){
            setUnauthorizedResponse(context, "error");
        }

        return null;
    }

    /**
     * @param requestContext
     * @param token
     * 验证token方法
     */
    private void verifyToken(RequestContext requestContext, String token) {
        String userId;
        if (StringUtils.isEmpty(token)) {
            setUnauthorizedResponse(requestContext, "NoToken");
        } else {
            try {
                userId = JWT.decode(token).getAudience().get(0);
                String s = stringRedisTemplate.opsForValue().get("internal_project_zcx:userToken:" + userId);
                log.info(s);
                if (s.isEmpty())
                {
                    setUnauthorizedResponse(requestContext, "ErrorToken");
                }
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(userId)).build();
                jwtVerifier.verify(token);
                log.info(token);
            } catch (JWTVerificationException e) {
                setUnauthorizedResponse(requestContext, "Token过期了");
//                throw new RuntimeException("token已过期");
            }

        }
    }

    /**
     * @param requestContext
     * @param msg
     * 返回前端报错信息
     */
    private void setUnauthorizedResponse(RequestContext requestContext, String msg) {
        requestContext.setSendZuulResponse(false);
        requestContext.getResponse().setCharacterEncoding("UTF-8");
        requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        requestContext.setResponseBody("{code:401,message:" + msg + "}");
    }
}
